package com.zbkj.service.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.zbkj.common.request.PageParamRequest;
import com.github.pagehelper.PageHelper;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.URLUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zbkj.common.exception.AppException;

import com.zbkj.common.result.CommonResultCode;
import com.zbkj.common.utils.CrmebDateUtil;
import com.zbkj.common.model.agent.Weather;
import com.zbkj.common.utils.qweather.QweatherUtil;
import com.zbkj.service.dao.WeatherDao;
import com.zbkj.service.service.WeatherService;

import com.zbkj.common.request.WeatherSaveRequest;
import com.zbkj.common.request.WeatherSearchRequest;
import com.zbkj.common.response.WeatherPageDataResponse;
import com.zbkj.common.response.WeatherDetailResponse;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* @author Caiyc
* @description WeatherServiceImpl 接口实现
* @date 2025-08-07
*/
@Service
public class WeatherServiceImpl extends ServiceImpl<WeatherDao, Weather> implements WeatherService {

    @Resource
    private WeatherDao dao;

    @Override
    public Boolean create(WeatherSaveRequest weatherSaveRequest) {
        Weather weather = new Weather();
        BeanUtils.copyProperties(weatherSaveRequest, weather, "id");
        boolean save = save(weather);
        if (!save) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "添加失败");
        }
        return save;
    }

    /**
     * 分页查询天气数据表
     *
     * @param request          请求参数
     * @param pageParamRequest 分页类参数
     * @return List<Weather>
     * @author Caiyc
     * @since 2025-08-07
     */
    @Override
    public List<WeatherPageDataResponse> getList(WeatherSearchRequest request, PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());

        //带 Weather 类的多条件查询
        LambdaQueryWrapper<Weather> lambdaQueryWrapper = Wrappers.lambdaQuery();
        // type 类型不能为空 bean中已经限制
        /*
        lambdaQueryWrapper.eq(Weather::getType, request.getType());

        if (ObjectUtil.isNotEmpty(request.getId()) && request.getId() > 0) {
            lambdaQueryWrapper.eq(Weather::getId, request.getId());
        }
        if (ObjectUtil.isNotEmpty(request.getName())) {
            lambdaQueryWrapper.like(Weather::getName, URLUtil.decode(request.getName()));
        }

        if (ObjectUtil.isNotEmpty(request.getStatus())) {
            lambdaQueryWrapper.eq(Weather::getStatus, request.getStatus());
        }
        if (ObjectUtil.isNotEmpty(request.getMethod())) {
            lambdaQueryWrapper.eq(Weather::getMethod, request.getMethod());
        }*/

        // 时间区间
        //if (ObjectUtil.isNotEmpty(request.getStarttime()) && ObjectUtil.isNotEmpty(request.getEndtime())) {
        //    lambdaQueryWrapper.between(Weather::getCreatetime, request.getStarttime(), request.getEndtime());
        //}
        // * -1 已结束 结束时间小于当前时间
        // * 1 进行中 结束时间大于当前时间 && 开始时间小于等于当前时间
        // * 0 未开始 开始时间大于当前时间
        /*
        if (ObjectUtil.isNotEmpty(request.getRunningStatus())) {
            switch (request.getRunningStatus()) {
                case -1:
                    lambdaQueryWrapper.lt(Weather::getEndtime, currentDate);
                    break;
                case 0:
                    lambdaQueryWrapper.gt(Weather::getStarttime, currentDate);
                    break;
                case 1:
                    lambdaQueryWrapper.ge(Weather::getEndtime, currentDate).le(Weather::getStarttime, currentDate);
                    break;
            }
        }*/

        lambdaQueryWrapper.orderByDesc(Weather::getCreateTime);
        List<Weather> weathers = dao.selectList(lambdaQueryWrapper);
        // 添加活动状态
        List<WeatherPageDataResponse> weatherResponses = new ArrayList<>();

        weathers.stream().forEach(x->{
            WeatherPageDataResponse weatherResponse = new WeatherPageDataResponse();
            BeanUtils.copyProperties(x, weatherResponse);
            //weatherResponse.setRunningStatus(x.getStarttime(), x.getEndtime(), currentDate);
            weatherResponses.add(weatherResponse);
        });
        return weatherResponses;
    }

    /**
    * 修改天气数据表
    * @param request
    * @return
    */
    @Override
    public boolean update(WeatherSaveRequest request) {
        if (ObjectUtil.isNull(request.getId()) || request.getId() < 1) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "请传入天气数据表ID");
        }
        getByIdException(request.getId());
        Weather weather = new Weather();
        BeanUtils.copyProperties(request, weather);
        return updateById(weather);
    }

    private Weather getByIdException(Integer id) {
        Weather weather = getById(id);
        if (ObjectUtil.isNull(weather)) {
            throw new AppException("天气数据表不存在");
        }
        if (weather.getIsDel()) {
            throw new AppException("天气数据表不存在");
        }
        return weather;
    }

    /**
    * 批量删除
    * @param idList
    * @return
    */
    @Override
    public boolean batchDelete(List<Integer> idList) {
    LambdaUpdateWrapper<Weather> luw = Wrappers.lambdaUpdate();
        luw.set(Weather::getIsDel, true);
        luw.in(Weather::getId, idList);
        boolean update = update(luw);
        if (!update) {
            throw new AppException(CommonResultCode.ERROR.setMessage("批量删除天气数据表失败"));
        }
        return true;
    }

    /**
    * 查询详情
    * @param id
    * @return
    */
    @Override
    public WeatherDetailResponse getDetails(Integer id) {
        LambdaQueryWrapper<Weather> lqw = Wrappers.lambdaQuery();
        lqw.eq(Weather::getIsDel, 0);
        lqw.last("limit 1");
        Weather weather = this.getOne(lqw);
        if (ObjectUtil.isNotNull(weather)) {
            WeatherDetailResponse response = new WeatherDetailResponse();
            BeanUtils.copyProperties(weather, response);
            return response;
        }
        return null;
    }

    @Override
    public void pullWeather(List<String> list) {
        List<Weather> weathers = new ArrayList<>();
        for (String location : list) {
            String json = QweatherUtil.pullData(location);
            if (StrUtil.isNotBlank(json)) {
                JSONObject jsonObject = JSONObject.parseObject(json);
                if (!jsonObject.getString("code").equals("200")) {
                    continue;
                }
                JSONObject data = jsonObject.getJSONObject("now");
                // 将 JSONObject 转为 User 对象
                Weather weather = data.toJavaObject(Weather.class);
                weather.setContent(json);
                weathers.add(weather);
            }
        }
        if (CollUtil.isNotEmpty(weathers)) {
            saveBatch(weathers);
        }
    }

}

